<script lang="ts" setup>
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { ref, computed, watch } from 'vue';
import allAreas from '../lib/pca-code.json';

export interface AreaData {
  code: string;
  name: string;
}

const province = ref<string>('');
const city = ref<string>('');
const area = ref<string>('');
const areas = ref(allAreas);

const getCities = computed(() => {
  return province.value ? areas.value.find((item) => item.code === province.value)?.children ?? [] : [];
});

const getAreas = computed(() => {
  return city.value ? getCities.value.find((item) => item.code === city.value)?.children ?? [] : [];
});

const emits = defineEmits(['change']);

watch(
  () => province.value,
  () => {
    city.value = '';
    area.value = '';
  },
);

watch(
  () => city.value,
  () => {
    area.value = '';
  },
);

watch(
  () => area.value,
  (val) => {
    if (val) {
      const provinceData: AreaData = {
        code: province.value,
        name: province.value && allAreas.find((item) => item.code === province.value)!.name,
      };

      const cityData: AreaData = {
        code: city.value,
        name: city.value && getCities.value.find((item) => item.code === city.value)!.name,
      };

      const areaData: AreaData = {
        code: val,
        name: val && getAreas.value.find((item) => item.code === val)!.name,
      };

      emits('change', {
        provinceData,
        cityData,
        areaData,
      });
    }
  },
);
</script>

<template>
  <div>
    <el-select v-model="province" placeholder="请选择省份">
      <el-option v-for="item in areas" :key="item.code" :value="item.code" :label="item.name"> </el-option>
    </el-select>
    <el-select v-model="city" placeholder="请选择市" :disabled="!province">
      <el-option v-for="item in getCities" :key="item.code" :value="item.code" :label="item.name"> </el-option>
    </el-select>
    <el-select v-model="area" placeholder="请选择县区" :disabled="!province || !city">
      <el-option v-for="item in getAreas" :key="item.code" :value="item.code" :label="item.name"> </el-option>
    </el-select>
  </div>
</template>

<style lang="scss" scoped></style>
